package com.ctgu.frequence.step1;

import com.ctgu.frequence.Utils.ValueComparator;

import java.util.*;

public class CountWord {
    public static Map<String,Integer> getWordMap(String str){
        str = str.toLowerCase();
        Map<String,Integer> map = new HashMap<String,Integer>(); // 定义一个哈希表
        String[] list = str.split("\\W+");
        int sum = 0; //统计单词总数
        for (int i = 0; i < list.length; i++) {
            if(!map.containsKey(list[i])){
                map.put(list[i], 1);
            }else{
                Integer num = map.get(list[i]);//有就增1
                map.put(list[i], num + 1);
            }
            sum++;
        }
        return map;
    }
    public static void countWord(String str){
        Map<String,Integer> map = getWordMap(str);
        //对map进行排序
        List<Map.Entry<String,Integer>> ls=new ArrayList<>();
        ls.addAll(map.entrySet());
        ValueComparator vc=new ValueComparator();
        Collections.sort(ls,vc);
        for(Map.Entry<String, Integer> item:ls){
            System.out.println(item.getKey()+"出现的次数为："+item.getValue());
        }
    }

}
